package cn.com.anypay.manager.payment.config;

import cn.com.anypay.manager.payment.service.PaymentService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

/**
 * 支付自动配置类
 *
 * 在应用启动时自动初始化支付渠道
 * 现在通过PaymentManager统一管理，更简洁清晰
 *
 * @author AnyPay Team
 * @version 1.0
 * @since 2025-07-05
 */
@Component
public class PaymentAutoConfiguration implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(PaymentAutoConfiguration.class);

    @Autowired
    private PaymentService paymentService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        logger.info("=== AnyPay 支付渠道抽象框架启动 ===");

        try {
            // 自动初始化测试渠道
            paymentService.initializeTestChannels();

            // 输出框架信息
            printFrameworkInfo();

            logger.info("=== AnyPay 支付渠道抽象框架启动完成 ===");

        } catch (Exception e) {
            logger.error("支付框架启动失败", e);
        }
    }

    /**
     * 输出框架信息
     */
    private void printFrameworkInfo() {
        logger.info("┌─────────────────────────────────────────────┐");
        logger.info("│            AnyPay 支付渠道抽象框架              │");
        logger.info("├─────────────────────────────────────────────┤");
        logger.info("│ 版本: 1.0.0                                 │");
        logger.info("│ 作者: AnyPay Team                           │");
        logger.info("│ 日期: 2025-07-05                           │");
        logger.info("├─────────────────────────────────────────────┤");

        // 获取所有渠道实现信息（按注册顺序）
        var implementationInfos = paymentService.getAllChannelImplementationInfoInOrder();

        logger.info("│ 已注册渠道实现数量: {}                       │", implementationInfos.length);

        // 按注册顺序显示每个渠道实现
        for (var implInfo : implementationInfos) {
            String defaultMarker = implInfo.isDefault() ? " (默认)" : "";
            logger.info("│ - {}{} ({})", implInfo.getImplementationKey(), defaultMarker, implInfo.getChannelName());
            logger.info("│   支持支付产品: {}", String.join(", ", implInfo.getSupportedPayProducts()));
        }

        logger.info("├─────────────────────────────────────────────┤");
        logger.info("│ 测试接口:                                    │");
        logger.info("│ POST /api/payment/init                      │");
        logger.info("│ GET  /api/payment/channels                  │");
        logger.info("│ POST /api/payment/test                      │");
        logger.info("└─────────────────────────────────────────────┘");
    }
}